package com.neusoft.databus.policy.event.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.databus.common.bean.ResourceBean;
import com.neusoft.databus.common.constant.DatabusErrorCode;
import com.neusoft.databus.policy.enums.EventStatus;
import com.neusoft.databus.policy.event.PolicyEventHandler;
import com.neusoft.databus.policy.model.Event;
import com.neusoft.databus.policy.model.EventAttribute;
import com.neusoft.databus.policy.model.Policy;
import com.neusoft.databus.policy.utils.PolicyUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 业务处理 设备异常，采集数据不全事件处理类
 *
 * @author naxiang
 */
@Slf4j
@Component("faultPolicyEventHandler")
public class FaultPolicyEventHandlerImpl extends PolicyEventHandlerImpl {

    @Override
    public void trigger(ResourceBean resourceBean, Date time, Policy policy,
            final List<Integer> expressionTrueSquence) {
        final String resourceCode = resourceBean.getCode();
        final String key = PolicyUtil.getEventKey(resourceCode, policy.getCode());
        Event event = null;
        try {
            event = this.getEvent(policy, resourceCode);
            final EventAttribute eventAttibute = event.getEventAttribute();
            eventAttibute.setLastTime(time);
            eventAttibute.setContent(this.eventContent(resourceCode, policy.getContentTemplate()));
            if (DatabusErrorCode.ERR_CODE_406005.equals(policy.getCode())) {
                final List<String> metricNames = this.checkMetricDataLost(resourceBean);
                eventAttibute.setContent(eventAttibute.getContent() + " 丢失指标名称：" + JsonUtils.pojoToJson(metricNames));
            }
            event.setStatus(EventStatus.UNFIXED);
            // event.setSort(EventSort.SYSTEM);// 系统告警
            synchronized (this.getLockInstance(resourceCode)) {
                if (!this.cacheService.isInCache(PolicyEventHandler.cacheName,
                        key)) {
                    this.cacheService.put(PolicyEventHandler.cacheName,
                            key, event.getCode());
                } else {
                    event.setCode(String.valueOf(this.cacheService.get(
                            PolicyEventHandler.cacheName, key)));
                }
            }
            this.policyEventBus.post(event);
        } catch (final Exception e) {
            FaultPolicyEventHandlerImpl.log.error("设备异常告警事件,策略code:{},资源code:{},产生异常{}",
                    policy.getCode(), resourceCode, e);
        } finally {
            // 置空大对象,以免内存增长过快
            time = null;
            event = null;
            resourceBean = null;
            policy = null;
        }

    }

    /**
     * 获取没采集到数据的指标名称
     *
     * @param resourceBean
     * @return
     */
    private List<String> checkMetricDataLost(final ResourceBean resourceBean) {
        return resourceBean.getMetrics().stream().filter(data -> !data.isParseSuccess()).map(data -> data.getName())
                .collect(Collectors.toList());
    }

}
